package com.sxbbc.seller.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.rest.RestFactory;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.basics.utils.validcode.VerifyCode;
import com.sxbbc.common.core.entity.jz.BBusiness;
import com.sxbbc.common.core.entity.jz.BLogin;
import com.sxbbc.common.core.entity.jz.BMenus;
import com.sxbbc.common.core.entity.jz.BOffline;
import com.sxbbc.common.core.entity.jz.Industry;
import com.sxbbc.common.core.enums.BusinessScopeEnums;
import com.sxbbc.common.core.enums.BusinessTypeEnums;
import com.sxbbc.common.core.enums.PayTypeEnums;
import com.sxbbc.common.core.service.BBusinessService;
import com.sxbbc.common.core.service.IBOfflineService;
import com.sxbbc.common.core.service.IIndustryDetailService;
import com.sxbbc.common.core.service.IIndustryService;
import com.sxbbc.common.core.service.IProcBrandInfoService;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.seller.common.MappingUtils;
import com.sxbbc.seller.service.BusinessService;
import com.sxbbc.seller.service.StatisService;
import com.sxbbc.seller.util.BusinessSession;
import com.sxbbc.seller.util.SystemLog;

/**
 * <p>
 * 商家  前端控制器
 * </p>
 *
 * @author YQQ
 * @since 2019-05-08
 */
@Controller
public class BusinessController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private BusinessService businessService;
	@Autowired
	private BBusinessService bBusinessService;
	@Autowired
	private IProcBrandInfoService brandInfoService;
	@Autowired
	private IIndustryService industryService;
	@Autowired
	private IIndustryDetailService industryDetailService;
	@Autowired
	private StatisService statisService;
	@Autowired
	private IBOfflineService bOfflineService;

	/***
	 * 商家登录页面
	 * @author YQQ
	 * @return
	 */
	@RequestMapping(value = MappingUtils.SHOW_LOGIN)
	public ModelAndView showLogin() {
		ModelAndView view = new ModelAndView(MappingUtils.SHOW_LOGIN);
		return view;
	}


	/**
     * 验证码
     * @param request
     * @param response
     * @author YQQ
     * @return void
     */
    @RequestMapping(value = MappingUtils.VERIFY_IMAGE)
    public void verifyImg(HttpServletRequest request, HttpServletResponse response) {
        VerifyCode verifyCode = VerifyCode.getInstance();
        verifyCode.createValidimg(response);
        BusinessSession.setValidCode(request, verifyCode.getText());
    }
    
    /**
     * 去登录操作
     *
     * @param request   session
     * @param login     登录名
     * @param password  密码
     * @param validCode 验证码
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.DO_LOGIN)
    @ResponseBody
    @SystemLog(methods = "商家登录", module = "商家管理")
    public RestResponse doLogin(HttpServletRequest request, String login,
                                String password, String validCode) {
        return businessService.doLogin(request, login, password, validCode);
    }
    
    /**
     * 首页
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.SHOW_INDEX)
    public ModelAndView showHome(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_INDEX);
        //菜单集合
        List<BMenus> menu = BusinessSession.getMenuList(request);
        BLogin bLogin = BusinessSession.getBLogin(request);
        view.addObject("list", menu);
        view.addObject("bLogin", bLogin);
        return view;
    }

    /**
     * 欢迎页面
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.SHOW_WELCOME)
    public ModelAndView showWelcome() {
    	Integer bid = BusinessSession.getBid(request);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_WELCOME);
        Map<String, Object> map = statisService.queryOrderMsg(bid);
        view.addObject("map", map);
        return view;
    }

    /**
     * 退出登录
     * @author YQQ
     */
    @RequestMapping(value = MappingUtils.EXIT)
    public ModelAndView exit(HttpServletRequest request){
        BusinessSession.exitSession(request);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_LOGIN);
        return view;
    }
    
    /**
     * 店铺详情页面
     * @return ModelAndView
     */
    @RequestMapping(value = MappingUtils.SHOW_BUSINESS_DETAIL)
    public ModelAndView showBusinessDetail (HttpServletRequest request) {
    	Integer bid = BusinessSession.getBid(request);
    	BBusiness business = businessService.getById(bid);
        String addrName = businessService.getAddrName(business.getProId(), business.getCityId(), business.getAreaId());
        addrName = addrName + " " + business.getAddressDetail();
        String industryName = "";
        String scope = BusinessTypeEnums.getName(business.getBType());
        // 主行业
        QueryWrapper<Industry> wrapper = new QueryWrapper<>();
        wrapper.eq("status",StaticUtils.STATUS_YES);
        List<Industry> industryList = industryService.list(wrapper);
        for (Industry industry : industryList) {
            if (CalcuUtils.getInstance().isEquals(industry.getId(),business.getIndustryId())) {
                industryName = industry.getName();
            }
        }
    	ModelAndView view = new ModelAndView(MappingUtils.SHOW_BUSINESS_DETAIL);
    	view.addObject("business", business);
    	view.addObject("addrName",addrName);
    	view.addObject("industryName",industryName);
    	view.addObject("scope",scope);
    	return view;
    }

    @RequestMapping(value = MappingUtils.APPLY_GUARANTEE)
    @ResponseBody
    public RestResponse applyGuarantee(HttpServletRequest request,Integer guarantee){
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("获取商家信息失败，请重新登录");
        }
        if (guarantee == null) {
            return GetRest.getFail("获取申请状态失败");
        }
        BBusiness bBusiness = bBusinessService.getById(bid);
        if (bBusiness == null) {
            return GetRest.getFail("商家不存在");
        }
        if (CalcuUtils.getInstance().isEquals(guarantee,StaticUtils.STATUS_SUCCESS)) {
            bBusiness.setGuarantee(StaticUtils.STATUS_SUCCESS);
            bBusinessService.updateById(bBusiness);
        }
        return GetRest.getSuccess("申请成功");
    }
    
    /**
     * 上传商家证件信息
     * @param frontImg
     * @param backImg
     * @param busImg
     * @return
     */
    @RequestMapping(value = MappingUtils.UPLOAD_BUS_IMG_BATCH)
    @ResponseBody
    public RestResponse uploadImage(@RequestParam(name = "frontImg", required = false) MultipartFile frontImg,
                                    @RequestParam(name = "backImg", required = false) MultipartFile backImg,
                                    @RequestParam(name = "busImg", required = false) MultipartFile busImg, 
                                    @RequestParam(name = "coverUrl", required = false)List<String> coverUrl){
        // 资料照片上传
        UploadUtils upload = UploadUtils.getInstance();
        RestUploadFileInfo result = null;
        Map<String,String> map = new HashMap<String, String>();
        if (frontImg != null) {
            result = upload.uploadFileQN(frontImg);
            if (result.isStatus()) {
                map.put("front",result.getData());
            } else if (!result.isStatus() && result != null) {
                return GetRest.getFail("身份证正面照片上传失败");
            }
        }
        if (backImg != null) {
            result = upload.uploadFileQN(backImg);
            if (result.isStatus()) {
                map.put("back",result.getData());
            } else if (!result.isStatus() && result != null) {
                return GetRest.getFail("身份证反面照片上传失败");
            }
        }
        if (busImg != null) {
            result = upload.uploadFileQN(busImg);
            if (result.isStatus()) {
                map.put("bus",result.getData());
            } else if (!result.isStatus() && result != null) {
                return GetRest.getFail("营业执照照片上传失败");
            }
        }
        String str = "";
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		if (coverUrl != null && coverUrl.size() > 0) {
			for (int i = 0; i < coverUrl.size(); i++) {
				HashMap<String, String> urlMap = new HashMap<String, String>();
				urlMap.put("url", coverUrl.get(i));
				list.add(urlMap);
			}
			str = JSON.toJSONString(list);
		} else {
			str = null;
		}
		map.put("coverUrl", str);
        return GetRest.getSuccess("success",map);
    }
    
    /**
     * 编辑商家信息
     * @param business
     * @return
     */
    @RequestMapping(value = MappingUtils.EDIT_BUSINESS)
    @ResponseBody
    public RestResponse editBusiness (HttpServletRequest request, BBusiness business) {
    	Integer bid = BusinessSession.getBid(request);
    	business.setId(bid);
    	return businessService.editBusiness(business);
    }
    
	/**
	 * 线下消费记录页面
	 * @return 
	 * @author xiaoky
	 */
	@RequestMapping(value = MappingUtils.SHOW_OFFLINE)
	public ModelAndView showOffline () {
		ModelAndView view = new ModelAndView(MappingUtils.SHOW_OFFLINE);
		List<PayTypeEnums> payTypeList = PayTypeEnums.queryList();
		view.addObject("payTypeList", payTypeList);
		return view;
	}
	
	/**
	 * 查询线下记录
	 * @param request
	 * @param page 分页
	 * @param bOffline 查询数据
	 * @return
	 * @author xiaoky
	 */
	@RequestMapping(value = MappingUtils.QUERY_OFFLINE_LIST)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryOfflineList (HttpServletRequest request, BasePage<BOffline> page, BOffline bOffline) {
    	Integer bid = BusinessSession.getBid(request);
    	bOffline.setBid(bid);
    	bOffline.setStatus(StaticUtils.STATUS_YES);
    	if (StringUtils.isNotBlank(bOffline.getQueryTime())) {
            String[] times = bOffline.getQueryTime().split("~");
            bOffline.setStart(times[0].trim());
            bOffline.setEnd(times[1].trim());
        }
    	bOfflineService.queryOfflineList(page, bOffline);
    	return RestFactory.success(page.getRecords(), page.getTotal());
    }
	
	/**
	 * 客服信息编辑页面
	 * @return
	 * @author xiaoky
	 */
	@RequestMapping(value = MappingUtils.SHOW_SERVICE_EDIT)
	public ModelAndView showServiceEdit (HttpServletRequest request) {
		ModelAndView view = new ModelAndView(MappingUtils.SHOW_SERVICE_EDIT);
		Integer bid = BusinessSession.getBid(request);
		BBusiness business = bBusinessService.getById(bid);
		if (business == null) {
			throw new ThrowJsonException("登录超时");
		}
		view.addObject("business", business);
		return view;
	}
	
	/**
	 * 编辑商家客服信息
	 * @param request
	 * @param business 
	 * @return
	 * @author xiaoky
	 */
	@RequestMapping(value = MappingUtils.BUSINESS_SERVICE_EDIT)
	@ResponseBody
	public RestResponse businessServiceEdit(HttpServletRequest request, BBusiness business, 
			@RequestParam(required = false)MultipartFile wxUrl) {
		Integer bid = BusinessSession.getBid(request);
		BBusiness queryBusiness = bBusinessService.getById(bid);
		if (queryBusiness == null) {
			throw new ThrowJsonException("登录超时");
		}
		CalcuUtils calcuUtils = CalcuUtils.getInstance();
		// 线下
		if (calcuUtils.isEquals(queryBusiness.getOnOff(), BusinessScopeEnums.OFFLINE.getId())) {
			if (StringUtils.isBlank(business.getLinkPhone())) {
				return GetRest.getFail("请输入线下店铺联系电话");
			}
		} else if (calcuUtils.isEquals(queryBusiness.getOnOff(), BusinessScopeEnums.ONLINE.getId())) {
			// 线上
			if (StringUtils.isBlank(business.getLinkQq())) {
				return GetRest.getFail("请输入线上联系QQ");
			}
			if (StringUtils.isBlank(business.getLinkWx())) {
				return GetRest.getFail("请输入线上联系微信");
			}
			UploadUtils upload = UploadUtils.getInstance();
			if (wxUrl != null) {
	            RestUploadFileInfo result = upload.uploadFileQN(wxUrl);
	            if (result.isStatus()) {
	            	business.setLinkWxUrl(result.getData());
	            } else if (!result.isStatus() && result != null) {
	                return GetRest.getFail("微信二维码上传失败");
	            }
	        }
		}
		business.setId(bid);
		boolean result = bBusinessService.updateById(business);
		if (!result) {
			return GetRest.getFail("保存失败");
		}
		return GetRest.getSuccess("保存成功");
	}
}
